package com.hui.wanxin.web.inteceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hui.wanxin.web.utils.JwtUtils;
import com.hui.wanxin.web.utils.R;
import com.hui.wanxin.web.utils.ResultCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


@Component
public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            String token = request.getHeader("token");
            if (token == null) {
                token = request.getParameter("token");
            }
            if(StringUtils.isNotBlank(token)){
                Claims claims = JwtUtils.checkToken(token);
                if(claims == null){
                    sendJsonMapper(response, R.sendMessage(ResultCode.NOTLOGIN, "登陆过期，请重新登陆"));
                    return false;
                }else {
                    String openid = (String) claims.get("openid");
                    request.setAttribute("openid",openid);
                    return true;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        sendJsonMapper(response, R.sendMessage(ResultCode.NOTLOGIN, "登陆过期，请重新登陆"));
        return false;
    }


    public static void sendJsonMapper(HttpServletResponse response, Object o) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.println(objectMapper.writeValueAsString(o));
            writer.close();
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
